package xin.alum.aim.coder;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import xin.alum.aim.constant.AimAttr;
import xin.alum.aim.model.Transportable;
import xin.alum.aim.model.Aim;

import java.util.List;

@ChannelHandler.Sharable
public class WebEncoder extends BaseEncoder<Transportable> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Transportable in, List<Object> list) {
        Aim.Agreement agreement = ctx.channel().attr(AimAttr.AGREEMENT).get();
        if (agreement == null) {
            logger.error("{} 未初始化通信协议", ctx.channel());
            return;
        }

        switch (agreement) {
            case Json:
            case Text:
                list.add(new TextWebSocketFrame(in.toJson()));
                break;
            case Binary:
            case ProtoBuf:
                list.add(new BinaryWebSocketFrame(in.toProto()));
                break;
            default:
                logger.error("{} 未知编码协议：{}", ctx.channel(), agreement);
                break;
        }
    }
}
